package com.mooltik;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.NotificationManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Toast;

import java.util.List;
import java.util.Set;

/**
 * Created by IntelliJ IDEA.
 * User: vit
 * Date: 23.02.11
 * Time: 18:28
 * To change this template use File | Settings | File Templates.
 */
public class SwitchActivity extends Activity {
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        ActivityManager am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RecentTaskInfo> recentTasks = am.getRecentTasks(5, ActivityManager.RECENT_WITH_EXCLUDED);

        boolean skipFirst = false;

        try {
            for (ActivityManager.RecentTaskInfo task : recentTasks) {

                if (task == null || task.baseIntent == null) {
                    continue;
                }

                //get last but one activity
                String action = task.baseIntent.getAction();
                if (action != null &&
                        (action.equals("android.intent.action.MAIN") || action.startsWith("android.settings"))) {

                    //skip home activity
                    Set<String> categories = task.baseIntent.getCategories();
                    if (categories != null && categories.contains("android.intent.category.HOME")) {
                        skipFirst = true;
                        continue;
                    }

                    if (!skipFirst) {
                        skipFirst = true;
                    } else {
                        task.baseIntent.setFlags(Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY);
                        startActivity(task.baseIntent);
                        break;
                    }
                }
            }

        } catch (Exception e) {
            Context context = getApplicationContext();
            int duration = Toast.LENGTH_SHORT;
            Toast toast = Toast.makeText(context, e.toString(), duration);
            toast.show();
        } finally {
            finish();
        }
    }
}